package com.storyroad.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.storyroad.responseClasses.StoryView;
import com.storyroad.utils.DBConnection;
import com.storyroad.utils.RecommendationGenerator;

/**
 * Servlet implementation class GetRecommendations
 */
public class GetRecommendations extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Generates recommended stories for a registered user. Please refer to {@link com.storyroad.utils.RecommendationGenerator}
	 * for a detailed explanation on how the recommendation system works. 
	 * @param request HttpServletRequest object that contains data coming from front-end
	 * @param response HttpServletResponse object that contains data which is prepared after processing the incoming data
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		PrintWriter out = response.getWriter();
		Connection conn = new DBConnection().connect();
		String f_username;
		String f_requestType = request.getParameter("request_type");
		if (f_requestType == null || !f_requestType.equals("Android")) {
			f_requestType = "Web";
			f_username = (String) request.getSession().getAttribute("username");
			if (f_username == null) {
				// Check whether this action is performed by a registered user. If not, the user is redirected to the login page.
				response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/LoginPage.jsp"));
				return;
			}
		} else {
			f_username = request.getParameter("username");
		}
		if (conn == null) {
			out.println("Connection error");
		} else {
			// Generate recommendations for this user
			RecommendationGenerator generator = new RecommendationGenerator(conn, f_username);
			ArrayList<StoryView> recommendations = generator.generateRecommendations();

			if (f_requestType.equals("Web")) {
				request.setAttribute("recommendations", recommendations);
				request.getRequestDispatcher("Recommendations.jsp").forward(request, response);
			} else if (f_requestType.equals("Android")) {
				JSONObject recommendationResultObject = new JSONObject();
				try {
					recommendationResultObject.put("recommendations",recommendations);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				out.print(recommendationResultObject.toString());
			} else {
				//DO NOTHING!
			}
			try {
				conn.close();
			} catch (SQLException e) {
				out.print(e.getMessage());
				e.printStackTrace();
			}
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
